<template>
    <h1>员工管理</h1>
    <div class="container">
        <el-form :inline="true" :model="empSearchForm">
            <el-form-item label="姓名">
                <el-input v-model="empSearchForm.name" placeholder="请输入员工姓名" clearable />
            </el-form-item>
            <el-form-item label="性别">
                <el-select v-model="empSearchForm.gender" placeholder="请选择员工性别" clearable>
                    <el-option label="男" value="1" />
                    <el-option label="女" value="2" />
                </el-select>
            </el-form-item>
            <el-form-item label="入职时间">
                <el-date-picker v-model="empSearchForm.date" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" unlink-panels clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchEmp">查询</el-button>
                <el-button type="info" @click="clearSearchForm">重置</el-button>
            </el-form-item>
        </el-form>
    </div>

    <div class="container">
        <el-button type="primary" @click="clickAddEmpBtn">+ 新增员工</el-button>
        <el-button type="danger" @click="deleteEmpByIds">- 批量删除</el-button>
    </div>

    <div class="container">
        <el-table :data="empList" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="name" label="姓名" width="120" align="center" />
            <el-table-column prop="gender" label="性别" width="120" align="center">
                <template #default="{ row }">{{ row.gender == 1 ? '男' : '女' }}</template>
            </el-table-column>
            <el-table-column prop="image" label="头像" width="120" align="center">
                <template #default="{ row }">
                    <el-image style="width: 50px; height: 50px;" :src="row.image" fit="cover"></el-image>
                </template>
            </el-table-column>
            <el-table-column prop="deptName" label="所属部门" width="120" align="center">
                <template #default="{ row }">
                    {{ row.deptName || "--" }}
                </template>
            </el-table-column>
            <el-table-column prop="job" label="职位" width="120" align="center">
                <template #default="{ row }">
                    {{ jobMap[row.job] || "--" }}
                </template>
            </el-table-column>
            <el-table-column prop="entryDate" label="入职日期" width="120" align="center" />
            <el-table-column prop="updateTime" label="最后操作时间" width="200" align="center">
                <template #default="{ row }">{{ parseTime(row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button link key="primary" type="primary" @click="editEmpBtn(scope.row.id)">编辑</el-button>
                    <el-button link key="danger" type="danger" @click="deleteEmpById(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <el-pagination :page-sizes="[5, 10, 20, 30, 50]" :background="background"
        layout="total, sizes, prev, pager, next, jumper" :total="empSearchForm.total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />

    <!-- 新增/编辑员工对话框 -->
    <el-dialog v-model="empDialogVisible" :title="empDialogTitle">
        <el-form ref="empFormRef" :model="empForm" :rules="empFormRules" label-width="80px">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="用户名" prop="username">
                        <el-input placeholder="请输入员工用户名，2～20个字" v-model="empForm.username" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="姓名" prop="name">
                        <el-input placeholder="请输入员工姓名，2～10个字" v-model="empForm.name" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="性别" prop="gender">
                        <el-select v-model="empForm.gender" placeholder="请选择性别" clearable>
                            <el-option v-for="gender in genderArr" :key="gender.value" :label="gender.name"
                                :value="gender.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="手机号" prop="phone">
                        <el-input placeholder="请输入员工手机号" v-model="empForm.phone" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="职位" prop="job">
                        <el-select v-model="empForm.job" placeholder="请选择职位" clearable>
                            <el-option v-for="job in jobArr" :key="job.value" :label="job.name" :value="job.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="薪资" prop="salary">
                        <el-input placeholder="请输入员工薪资" v-model="empForm.salary" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="所属部门" prop="deptId">
                        <el-select v-model="empForm.deptId" placeholder="请选择所属部门" clearable>
                            <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="dept.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="入职日期" prop="entryDate">
                        <el-date-picker v-model="empForm.entryDate" type="date" placeholder="选择入职日期" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="头像" prop="image">
                        <el-upload class="avatar-uploader" action="/api/upload" :headers="{'token': token}" :show-file-list="false"
                            :on-success="handleUploadImageSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="empForm.image" :src="empForm.image" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="工作经历" prop="exprList">
                        <el-button type="success" size="small" @click="addExpr">添加工作经历</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20" v-for="(expr, index) in empForm.exprList" :key="index">
                <el-row :gutter="3">
                    <el-col :span="10">
                        <el-form-item size="small" label="时间" label-width="80px">
                            <el-date-picker v-model="expr.date" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD"
                                value-format="YYYY-MM-DD"></el-date-picker>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item size="small" label="公司" label-width="60px">
                            <el-input v-model="expr.company" placeholder="请输入公司名称"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item size="small" label="职位" label-width="60px">
                            <el-input v-model="expr.job" placeholder="请输入职位"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="2">
                        <el-form-item size="small" label-width="0px">
                            <el-button type="danger" @click="empForm.exprList.splice(index, 1)">- 删除</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="empDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEmp">保存</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { getAllEmpApi, addEmpApi, getEmpById, updateEmp, deleteEmpApi } from '@/api/emp.js';
import { getAllDeptList } from '@/api/dept.js';
import { parseTime } from '@/utils/date.js';
import { onMounted, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'; 

const empSearchForm = ref({
    name: '',
    gender: '',
    date: [],
    begin: '',
    end: '',
    page: 1,
    pageSize: 10,
    total: 0,
})
const empList = ref([]);
const background = ref(true)
const empDialogVisible = ref(false);
const empFormRef = ref(null);
const empForm = ref({
    image: '',
    username: '',
    name: '',
    gender: '',
    job: '',
    entryDate: '',
    deptId: '',
    phone: '',
    salary: '',
    exprList: []
});
const deptList = ref([]);
const empDialogTitle = ref('');
const selectedEmpIds = ref([]);
const token = ref('')

const jobMap = ref({
    1: '班主任',
    2: '讲师',
    3: '学工主管',
    4: '教研主管',
    5: '咨询师',
})

const genderArr = ref([
    { name: '男', value: 1 },
    { name: '女', value: 2 },
])

const jobArr = ref([
    { name: '班主任', value: 1 },
    { name: '讲师', value: 2 },
    { name: '学工主管', value: 3 },
    { name: '教研主管', value: 4 },
    { name: '咨询师', value: 5 },
])

const empFormRules = ref({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }, { min: 2, max: 20, message: '用户名长度在2~20个字符', trigger: 'blur' }],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }, { min: 2, max: 10, message: '姓名长度在2~10个字符', trigger: 'blur' }, { pattern: /^[\u4e00-\u9fa5]{2,10}$/, message: '请输入正确的姓名', trigger: 'blur' }],
    gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }]
})

onMounted(() => {
    searchEmp();
    getAllDeptList().then(res => {
        if (res.code === 1) {
            deptList.value = res.data;
        }
    });
    getToken();
});

const getToken = () => {
    let loginUser = JSON.parse(localStorage.getItem('loginUser'));
    if (loginUser && loginUser.token) {
        token.value = loginUser.token;
    }
}

const searchEmp = async () => {
    const { name, gender, begin, end, page, pageSize } = empSearchForm.value;
    const res = await getAllEmpApi(name, gender, begin, end, page, pageSize);
    if (res.code == 1) {
        empSearchForm.value.total = res.data.total;
        empList.value = res.data.rows;
    }
}

const clearSearchForm = () => {
    empSearchForm.value = {
        name: '',
        gender: '',
        date: [],
        begin: '',
        end: '',
        page: 1,
        pageSize: 10,
        total: 0,
    }
    searchEmp();
}

const handleSizeChange = (val) => {
    empSearchForm.value.pageSize = val;
    searchEmp();
}

const beforeAvatarUpload = (rowFile) => {
    if (rowFile.type.indexOf('image') == -1) {
        ElMessage.error('上传文件只能是图片格式!');
        return false;
    }
    if (rowFile.size > 2 * 1024 * 1024) {
        ElMessage.error('上传文件大小不能超过 2MB!');
        return false;
    }
    return true;
}

const handleCurrentChange = (val) => {
    empSearchForm.value.page = val;
    searchEmp();
}

const clickAddEmpBtn = () => {
    empDialogVisible.value = true;
    empDialogTitle.value = '新增员工';
    // 清空表单
    empForm.value = {
        image: '',
        username: '',
        name: '',
        gender: '',
        job: '',
        entryDate: '',
        deptId: '',
        phone: '',
        salary: '',
        exprList: []
    };
    // 清空校验
    if (empFormRef.value) {
        empFormRef.value.clearValidate();
    }
}

const editEmpBtn = (id) => {
    empDialogVisible.value = true;
    empDialogTitle.value = '编辑员工';
    // 清空校验
    if (empFormRef.value) {
        empFormRef.value.clearValidate();
    }
    getEmpById(id).then(res => {
        if (res.code === 1) {
            empForm.value = res.data;
            empForm.value.exprList.forEach(expr => {
                expr.date = [expr.begin, expr.end];
            });
        }
    });
}

const saveEmp = () => {
    if (!empFormRef.value) {
        ElMessage.error('表单不存在');
        return;
    }
    empFormRef.value.validate(async (valid) => {
        if (valid) {
            // 处理工作经历数组
            empForm.value.exprList.forEach(expr => {
                expr.begin = expr.date[0];
                expr.end = expr.date[1];
                // delete expr.date;
            });
            let res;
            if (!empForm.value.id) {
                res = await addEmpApi(empForm.value);
            } else {
                res = await updateEmp(empForm.value);
            }
            if (res.code === 1) {
                ElMessage.success('添加员工成功');
                empDialogVisible.value = false;
                searchEmp();
            } else {
                ElMessage.error(res.msg);
            }
        } else {
            ElMessage.error('请检查表单填写是否正确');
            return false;
        }
    });
}

const handleUploadImageSuccess = (response) => {
    empForm.value.image = response.data;
}

const addExpr = () => {
    empForm.value.exprList.push({
        company: '',
        job: '',
        begin: '',
        end: '',
        date: ''
    });
}

const deleteEmpById = (id) => {
    ElMessageBox.confirm('确定要删除该员工吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        let res = await deleteEmpApi(id);
        if (res.code === 1) {
            ElMessage.success('删除成功');
            searchEmp();
        } else {
            ElMessage.error(res.msg);
        }
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
}

const handleSelectionChange = (selections) => {
    selectedEmpIds.value = selections.map(item => {
        return item.id;
    });
}

const deleteEmpByIds = () => {
    ElMessageBox.confirm('确定要删除该员工吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        if (!selectedEmpIds.value.length) {
            ElMessage.info('请选择要删除的员工');
            return;
        }
        let res = await deleteEmpApi(selectedEmpIds.value);
        if (res.code === 1) {
            ElMessage.success('删除成功');
            searchEmp();
        } else {
            ElMessage.error(res.msg);
        }
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
}

watch(() => empSearchForm.value.date, (newValue, oldValue) => {
    if (newValue.length == 2) {
        empSearchForm.value.begin = newValue[0];
        empSearchForm.value.end = newValue[1];
    } else {
        empSearchForm.value.begin = '';
        empSearchForm.value.end = '';
    }
});
</script>

<style scoped>
.container {
    margin: 20px 0;
}

.avatar {
    height: 40px;
}

.avatar-uploader .avatar {
    width: 78px;
    height: 78px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    text-align: center;
    /* 添加灰色的虚线边框 */
    border: 1px dashed var(--el-border-color);
}
</style>
